package tencent_practice;

import structure.ListNode;

/**
 * 两数相加，数字的每一位都是在链表上
 */
public class Tencent_2_addTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) {
            return l1 == null ? reverseList(l2) : reverseList(l1);
        }
        ListNode dummy = new ListNode();
        ListNode curr = dummy;
        int arr = 0;
        while (l1 != null || l2 != null) {
            int node1 = l1 == null ? 0 : l1.val;
            int node2 = l2 == null ? 0 : l2.val;
            int sum = node1 + node2 + arr;
            arr = sum / 10;
            int temp = sum % 10;

            curr.next = new ListNode(temp);

            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
            curr = curr.next;
        }
        if (arr != 0) {
            curr.next = new ListNode(arr);
        }
        return dummy.next;

    }

    public ListNode reverseList(ListNode node) {
        if (node == null || node.next == null) {
            return node;
        }
        ListNode newNode = reverseList(node.next);
        node.next.next = node;
        node.next = null;
        return newNode;
    }
}
